package ru.spb.osll.myfit.server.chart;

import org.apache.log4j.Logger;
import ru.spb.osll.myfit.common.TextParsingTools;
import ru.spb.osll.myfit.common.chart.ChartData;
import ru.spb.osll.myfit.server.Configurator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ChartHandler {
  private String m_testResultsDirectory;
  private static final ChartXMLSerializer XML_SERIALIZER = new ChartXMLSerializer();
  private static Logger m_logger = Logger.getLogger(ChartHandler.class);

  public ChartHandler() {
    Configurator configurator = Configurator.getInstance();
    m_testResultsDirectory = configurator.getTestResultsDirectory();
  }

  public String getChartDirectoryPath(String pageId) {
    return m_testResultsDirectory + File.separator + pageId + File.separator + "charts" + File.separator;
  }

  public List<ChartData> getChartDataList(List<String> ids) {
    List<ChartData> chartRenderDataList = new ArrayList<ChartData>();
    for (String id : ids) {
      StringBuilder dataFile = new StringBuilder(getChartDirectoryPath(id.substring(0, id.indexOf(TextParsingTools.TABLE_CELL_SEPARATOR))));
      dataFile.append(id.substring(id.indexOf(TextParsingTools.TABLE_CELL_SEPARATOR) + 1));

      ChartRenderData renderData;
      try {
        renderData = XML_SERIALIZER.fromXML(new FileInputStream(dataFile.toString()));
      }
      catch (Exception e) {
        m_logger.error("Chart deserialization error", e);
        continue;
      }
      chartRenderDataList.add(new ChartData(renderData.getCurves(), renderData.getName(), renderData.getHorizontalLabel(), renderData.getVerticalLabel(), renderData.getTitle()));
    }

    return chartRenderDataList;
  }


  public List<String> getChartList(String id) {
    String directoryPath = getChartDirectoryPath(id);

    File directory = new File(directoryPath);

    String[] dataFiles = directory.list(new FilenameFilter() {
      @Override
      public boolean accept(File dir, String name) {
        return name.endsWith("chart");
      }
    });

    return new ArrayList<String>(Arrays.asList(dataFiles));
  }
}
